/**
 * 
 */
package com.haisen.lee.serviceimpl;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.haisen.lee.domain.ResultNode;
import com.haisen.lee.service.IResultDomParser;

/**
 * @author haisen lee
 * 
 */
public class ResultDomParser implements IResultDomParser {

	private List<ResultNode<String>> resultQueue = new LinkedList<ResultNode<String>>();

	/**
	 * 
	 */
	public ResultDomParser() {
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.haisen.lee.service.IResultDomParser#resultContentExtractor(org.w3c
	 * .dom.Node)
	 */
	public void resultContentExtractor(Node root) throws Exception {
		for (Iterator<ResultNode<String>> queueIterator = resultQueue
				.iterator(); queueIterator.hasNext();) {
			ResultNode<String> resultNode = queueIterator.next();
			resultNode.setTraversalFlag(true);
			resultQueue.remove(0);
			resultQueue.addAll(0, resultNode.getChildrenNode());
			boolean loopNodeFlag = Boolean.parseBoolean(resultNode
					.getAttributes().get("loopNodeFlag").getAttributeValue());
			boolean textNodeFlag = Boolean.parseBoolean(resultNode
					.getAttributes().get("textNodeFlag").getAttributeValue());
			boolean expandNodeFlag = Boolean.parseBoolean(resultNode
					.getAttributes().get("expandNodeFlag").getAttributeValue());
			if (loopNodeFlag) {
				Node broherNode = null;
				do {
					broherNode = root.getNextSibling();
					resultContentExtractor(broherNode);
				} while (!broherNode.getNodeName().equalsIgnoreCase(
						resultNode.getTag()));

			}
			if (textNodeFlag) {
				// TODO print
				System.out.println(root.getTextContent());
			}
			if (expandNodeFlag) {
				NodeList childNodes = root.getChildNodes();
				for (int i = 0; i < childNodes.getLength(); i++) {
					Node childNode = childNodes.item(i);
					List<ResultNode<String>> resultchildNodes = resultNode
							.getChildrenNode();
					for (ResultNode<String> resultchildNode : resultchildNodes) {
						if (childNode.getNodeName().equalsIgnoreCase(
								resultchildNode.getTag())) {
							resultContentExtractor(childNode);
							break;
						}
					}
				}
			}

		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.haisen.lee.service.IResultDomParser#resultInit()
	 */
	public void resultInit() {

	}

	public List<ResultNode<String>> getResultQueue() {
		return resultQueue;
	}

	public void setResultQueue(List<ResultNode<String>> resultQueue) {
		this.resultQueue = resultQueue;
	}

}
